package com.yds.ydsdatasetbackend.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yds.ydsdatasetbackend.annotation.AuthCheck;
import com.yds.ydsdatasetbackend.common.BaseResponse;
import com.yds.ydsdatasetbackend.common.Category;
import com.yds.ydsdatasetbackend.common.DeleteRequest;
import com.yds.ydsdatasetbackend.common.ResultUtils;
import com.yds.ydsdatasetbackend.constant.UserConstant;
import com.yds.ydsdatasetbackend.exception.BusinessException;
import com.yds.ydsdatasetbackend.exception.ErrorCode;
import com.yds.ydsdatasetbackend.exception.ThrowUtils;
import com.yds.ydsdatasetbackend.model.dto.file.variables.FileVariablesQueryRequest;
import com.yds.ydsdatasetbackend.model.dto.file.variables.FileVariablesUpdateRequest;
import com.yds.ydsdatasetbackend.model.dto.patient.PatientGroupAddRequest;
import com.yds.ydsdatasetbackend.model.dto.patient.PatientGroupUpdateRequest;
import com.yds.ydsdatasetbackend.model.entity.FileVariables;
import com.yds.ydsdatasetbackend.model.entity.Patient;
import com.yds.ydsdatasetbackend.model.entity.PatientGroup;
import com.yds.ydsdatasetbackend.model.entity.User;
import com.yds.ydsdatasetbackend.model.vo.FileVariablesVO;
import com.yds.ydsdatasetbackend.model.vo.PatientGroupVO;
import com.yds.ydsdatasetbackend.service.FileVariablesService;
import com.yds.ydsdatasetbackend.service.PatientGroupService;
import com.yds.ydsdatasetbackend.service.PatientService;
import com.yds.ydsdatasetbackend.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/patient/group")
public class PatientGroupController {

    @Resource
    private PatientGroupService patientGroupService;

    @Resource
    private UserService userService;
    @Resource
    private PatientService patientService;


    /**
     * 添加分组
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.USER_LOGIN_STATE)
    public BaseResponse<PatientGroupVO> addPatientGroup(@RequestBody PatientGroupAddRequest patientGroupAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(StrUtil.isBlank(patientGroupAddRequest.getGroupName()), ErrorCode.PARAMS_ERROR,"分组名称不能为空");
        PatientGroup patientGroup = new PatientGroup();
        BeanUtil.copyProperties(patientGroupAddRequest, patientGroup);
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.PARAMS_ERROR,"用户不存在");
        patientGroup.setUserId(loginUser.getId());
        if(patientGroup.getParentId() == null) patientGroup.setParentId(-1L);
        boolean save = patientGroupService.save(patientGroup);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(PatientGroupVO.objToVo(patientGroup));
    }


    /**
     * 获取树形结构
     */
    @GetMapping("/getTree")
    @AuthCheck(mustRole = UserConstant.USER_LOGIN_STATE)
    public BaseResponse<List<Category>> getPatientGroup(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.PARAMS_ERROR,"用户不存在");
        return ResultUtils.success(patientGroupService.getTree(loginUser.getId()));
    }

    /**
     * 修改分组
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.USER_LOGIN_STATE)
    public BaseResponse<PatientGroupVO> updatePatientGroup(@RequestBody PatientGroupUpdateRequest patientGroupUpdateRequest, HttpServletRequest request) {
        if (patientGroupUpdateRequest == null || patientGroupUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        ThrowUtils.throwIf(StrUtil.isBlank(patientGroupUpdateRequest.getGroupName()), ErrorCode.PARAMS_ERROR,"分组名称不能为空");
        PatientGroup patientGroup = patientGroupService.getById(patientGroupUpdateRequest.getId());
        ThrowUtils.throwIf(patientGroup == null, ErrorCode.NOT_FOUND_ERROR);

        BeanUtil.copyProperties(patientGroupUpdateRequest, patientGroup);
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.PARAMS_ERROR,"用户不存在");
        if(!Objects.equals(loginUser.getId(), patientGroup.getUserId())) throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无法修改他人数据");
        patientGroup.setUserId(loginUser.getId());

        if(patientGroup.getParentId() == null) patientGroup.setParentId(-1L);
        boolean save = patientGroupService.updateById(patientGroup);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(PatientGroupVO.objToVo(patientGroup));
    }

    /**
     * 删除分组
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.USER_LOGIN_STATE)
    public BaseResponse<Boolean> deletePatientGroup(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //校验该分组是否被利用
        QueryWrapper<PatientGroup> queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("parentId",deleteRequest.getId());
        boolean exists1 = patientGroupService.exists(queryWrapper1);
        QueryWrapper<Patient> queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("groupId",deleteRequest.getId());
        boolean exists2 = patientService.exists(queryWrapper2);
        if(exists1 || exists2) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "分组被使用");
        }
        boolean b = patientGroupService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 通过id获取分组信息
     */
    @GetMapping("/get/vo")
    @AuthCheck(mustRole = UserConstant.USER_LOGIN_STATE)
    public BaseResponse<PatientGroupVO> getPatientGroupById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        PatientGroup patientGroup = patientGroupService.getById(id);
        ThrowUtils.throwIf(patientGroup == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(PatientGroupVO.objToVo(patientGroup));
    }

}
